package com.summer.servlet.user;

import com.alibaba.fastjson.JSONArray;
import com.mysql.jdbc.StringUtils;
import com.summer.pojo.Role;
import com.summer.pojo.User;
import com.summer.service.role.RoleService;
import com.summer.service.role.RoleServiceImpl;
import com.summer.service.user.UserService;
import com.summer.service.user.UserServiceImpl;
import com.summer.util.Constants;
import com.summer.util.PageSupport;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 作者:夏天
 * qq:1205232048
 */
//实现Servlet复用
@WebServlet("/jsp/user.do")
public class UserServlet extends HttpServlet {
    private static final long serialVersionUID = 444208147286197100L;

    /**
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if(method != null && method.equals("savepwd")){
            this.modifyPasswordByid(req,resp);
        }else if(method != null && method.equals("pwdmodify")){
            this.verifyOldPassword(req,resp);
        }else if(method != null && method.equals("query")){
            this.userQuery(req,resp);
        }else if(method != null && method.equals("add")){
            this.addUser(req,resp);
        }else if(method != null && method.equals("deluser")){
            this.deleteUserById(req,resp);
        }else if(method != null && method.equals("ucexist")){
            this.selectUserCodeExist(req,resp);
        }else if (method != null && method.equals("getrolelist")) {
            this.getRoleList(req, resp);
        }else if (method != null && method.equals("modifyexe")) {
            this.modify(req, resp);
        }else if (method != null && method.equals("modify")) {
            this.getUserById(req, resp, "usermodify.jsp");
        }else if (method != null && method.equals("view")) {
            this.getUserById(req, resp, "userview.jsp");
        }

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    /**
     *根据用户Id得到用户
     * @param req
     * @param resp
     * @param url
     */
    private void getUserById(HttpServletRequest req, HttpServletResponse resp, String url) {
        String id = req.getParameter("uid");
        if (!StringUtils.isNullOrEmpty(id)) {
            //调用后台方法得到user对象
            UserService userService = new UserServiceImpl();
            User user = userService.getUserById(id);
            req.setAttribute("user", user);
            try {
                req.getRequestDispatcher(url).forward(req, resp);
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 修改用户
     * @param req
     * @param resp
     * @throws IOException
     * @throws ServletException
     */
    private void modify(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        String id = req.getParameter("uid");
        String userName = req.getParameter("userName");
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String userRole = req.getParameter("userRole");

        User user = new User();
        user.setId(Integer.valueOf(id));
        user.setUserName(userName);
        user.setGender(Integer.valueOf(gender));
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        user.setPhone(phone);
        user.setAddress(address);
        user.setUserRole(Integer.valueOf(userRole));
        user.setModifyBy(((User) req.getSession().getAttribute(Constants.USER_SESSION)).getId());
        user.setModifyDate(new Date());

        UserService userService = new UserServiceImpl();
        if (userService.modifyUser(user)) {
            resp.sendRedirect(req.getContextPath() + "/jsp/user.do?method=query");
        } else {
            req.getRequestDispatcher("usermodify.jsp").forward(req, resp);
        }
    }

    /**
     * 得到角色列表
     * @param req
     * @param resp
     * @throws IOException
     */
    private void getRoleList(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        List<Role> roleList = null;
        RoleService roleService = new RoleServiceImpl();
        roleList = roleService.getRoleList();
        //把roleList转换成json对象输出
        resp.setContentType("application/json");
        PrintWriter outPrintWriter = null;
        outPrintWriter = resp.getWriter();
        outPrintWriter.write(JSONArray.toJSONString(roleList));
        outPrintWriter.flush();
        outPrintWriter.close();
    }

    /**
     * 通过用户编码判断改用户是否存在 前端js中有一个ajax异步请求 能实时的检查
     * @param req
     * @param resp
     */
    public void selectUserCodeExist(HttpServletRequest req, HttpServletResponse resp){
        //判断用户账号是否可用
        String userCode = req.getParameter("userCode");

        HashMap<String, String> resultMap = new HashMap<String, String>();
        if (StringUtils.isNullOrEmpty(userCode)) {
            //userCode == null || userCode.equals("")
            resultMap.put("userCode", "exist");
        } else {
            UserService userService = new UserServiceImpl();
            User user = userService.selectUserCodeExist(userCode);
            if (null != user) {
                resultMap.put("userCode", "exist");
            } else {
                resultMap.put("userCode", "notexist");
            }
        }

        //把resultMap转为json字符串以json的形式输出
        //配置上下文的输出类型
        resp.setContentType("application/json");
        //从response对象中获取往外输出的writer对象
        PrintWriter outPrintWriter = null;
        try {
            outPrintWriter = resp.getWriter();
            //把resultMap转为json字符串 输出
            outPrintWriter.write(JSONArray.toJSONString(resultMap));
            outPrintWriter.flush();//刷新
        } catch (IOException e) {
            e.printStackTrace();
            outPrintWriter.close();//关闭流
        }


    }

    /**
     * 根据用户Id删除用户
     * @param req
     * @param resp
     */
    public void deleteUserById(HttpServletRequest req, HttpServletResponse resp){
        String id = req.getParameter("uid");
        Integer delId = 0;
        try {
            delId = Integer.parseInt(id);
        } catch (Exception e) {
            // TODO: handle exception
            delId = 0;
        }
        HashMap<String, String> resultMap = new HashMap<String, String>();
        if (delId <= 0) {
            resultMap.put("delResult", "notexist");
        } else {
            UserService userService = new UserServiceImpl();
            if (userService.deleteUserById(delId)) {
                resultMap.put("delResult", "true");
            } else {
                resultMap.put("delResult", "false");
            }
        }

        //把resultMap转换成json对象输出
        resp.setContentType("application/json");
        PrintWriter outPrintWriter = null;
        try {
            outPrintWriter = resp.getWriter();
            outPrintWriter.write(JSONArray.toJSONString(resultMap));
            outPrintWriter.flush();
        } catch (IOException e) {
            e.printStackTrace();
            outPrintWriter.close();
        }

    }

    /**
     * 添加用户
     * @param req
     * @param resp
     * @throws IOException
     * @throws ServletException
     */
    public void addUser(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        //从前端获取信息
        String userCode = req.getParameter("userCode");//用户编码
        String userName = req.getParameter("userName");//用户名称
        String userPassword = req.getParameter("userPassword");//用户密码
        String gender = req.getParameter("gender");//用户性别
        String birthday = req.getParameter("birthday");//出生日期
        String phone = req.getParameter("phone");//用户电话
        String address = req.getParameter("address");//用户地址
        String userRole = req.getParameter("userRole");//用户角色
        //创建一个用户
        User user = new User();
        //给用户赋值
        user.setUserCode(userCode);
        user.setUserName(userName);
        user.setUserPassword(userPassword);
        user.setAddress(address);

        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {
            e.printStackTrace();
        }

        user.setGender(Integer.valueOf(gender));
        user.setPhone(phone);
        user.setUserRole(Integer.valueOf(userRole));
        user.setCreationDate(new Date());
        user.setCreatedBy(((User)req.getSession().getAttribute(Constants.USER_SESSION)).getId());
        //创建用户业务层去调用添加用户方法
        UserServiceImpl userService = new UserServiceImpl();
        if(userService.addUser(user)){//添加成功
            resp.sendRedirect(req.getContextPath() + "/jsp/user.do?method=query");//重定向到查询页面
        }else {
            req.getRequestDispatcher("useradd.jsp").forward(req, resp);//转发到用户添加页面
        }

    }

    /**
     * //给前端展示用户查询
     * //先要得到用户查询人数  用户查询列表  角色查询列表
     * //1.用户查询人数 要得到用户姓名 用户角色
     * //2.用户查询列表 要得到用户姓名 用户角色 当前页数 页面数据条数
     * //3.角色查询列表
     * @param req
     * @param resp
     * @throws IOException
     */
    public void userQuery(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        int userRoleId = 0;
        List<User> userList = new ArrayList<User>();
        UserServiceImpl userService = new UserServiceImpl();//得到用户业务层
        String userName = req.getParameter("queryname");//去前端获取用户姓名
        String userRole = req.getParameter("queryUserRole");//去前端获取用户角色
        System.out.println("UserServlet->userQuery->userRole = " + userRole);
        if(userName == null){//判断用户姓名
            userName = "";
        }
        if((userRole != null) && (!userRole.equals(""))){//判断用户角色
            userRoleId = Integer.parseInt(userRole);
            System.out.println("为什么你不走这里呢");
        }
        System.out.println("UserServlet->userQuery->userRoleId = " + userRoleId);
        int userCount = userService.getUserCount(userName, userRoleId);//得到查询的人数
        String pageIndex = req.getParameter("pageIndex");//去前端获取页码
        int currentPageNo = 1;//设置当前页
        if(pageIndex != null){
            try {
                currentPageNo = Integer.valueOf(pageIndex);
            } catch (NumberFormatException e) {
                resp.sendRedirect("error.jsp");
            }
            //Integer. valueOf()可以将基本类型int转换为包装类型Integer，或者将String转换成Integer，String如果为Null或“”都会报错
        }
        PageSupport pageSupport = new PageSupport();
        pageSupport.setPageSize(Constants.PAGESIZE);//一页有多少条数据
        pageSupport.setCurrentPageNo(currentPageNo);//当前页
        pageSupport.setTotalCount(userCount);//总数量
        int totalPageCount = pageSupport.getTotalPageCount();//有多少页
        //控制首页和尾页
        if (currentPageNo < 1) {//如果页面小于第一页，就显示第一页
            currentPageNo = 1;
        } else if (currentPageNo > totalPageCount) {//如果当前页面大于最后一页，当前页等于最后一页即可
            currentPageNo = totalPageCount;
        }
        //获取用户列表展示
        userList = userService.getUserList(userName, userRoleId, currentPageNo, Constants.PAGESIZE);
        req.setAttribute("userList", userList);
        System.out.println("UserServlet->userQuery->userList = " + userList);
        //获取角色列表
        List<Role> roleList = null;
        RoleService roleService = new RoleServiceImpl();
        roleList = roleService.getRoleList();
        //传给前端
        req.setAttribute("roleList", roleList);
        req.setAttribute("queryUserName", userName);
        req.setAttribute("queryUserRole", userRole);
        req.setAttribute("totalPageCount", totalPageCount);
        req.setAttribute("totalCount", userCount);
        req.setAttribute("currentPageNo", currentPageNo);

        try {
            req.getRequestDispatcher("userlist.jsp").forward(req, resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过ajax验证老密码是否正确
     * @param req
     * @param resp
     */
    public void verifyOldPassword(HttpServletRequest req, HttpServletResponse resp){
        //得到前端的旧密码
        String oldpassword = req.getParameter("oldpassword");
        //得到该对象
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        //创建一个map用来存放前端的结果集
        HashMap<String, String> resultMap = new HashMap<String, String>();
        if(o == null){//session过期了 去xml中注册session存活时间
            resultMap.put("result","sessionerror");
        }else if(oldpassword.equals("")){
            resultMap.put("result","error");
        }else {
            if(((User)o).getUserPassword().equals(oldpassword)){
                resultMap.put("result","true");
            }else {
                resultMap.put("result","false");
            }
        }

        try {
            resp.setContentType("application/json");
            PrintWriter writer = resp.getWriter();
            writer.write(JSONArray.toJSONString(resultMap));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 修改用户密码
     * @param req
     * @param resp
     */
    public void modifyPasswordByid(HttpServletRequest req, HttpServletResponse resp){
        //根据session得到用户
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        //得到新密码
        String newpassword = req.getParameter("newpassword");
        if(o != null && !StringUtils.isNullOrEmpty(newpassword)){
            //创建一个service对象 给servlet层调用方法
            UserServiceImpl userService = new UserServiceImpl();
            boolean b = userService.modifyPasswordById(((User) o).getId(), newpassword);
            if(b){
                req.setAttribute(Constants.MESSAGE,"密码修改成功");
                req.getSession().removeAttribute(Constants.USER_SESSION);
            }else {
                req.setAttribute(Constants.MESSAGE,"密码修改失败");
            }
        }else{
            req.setAttribute(Constants.MESSAGE,"密码修改失败");
        }
        //无论修改成功还是失败都转发到登录页面
        try {
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
